package org.jz.gae.redbook.spb.server.controller;

import java.util.HashMap;
import java.util.Map;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

abstract public class AbstractCasheGoogle<V>
{
	private Map<Key, V> cashe = new HashMap<Key, V>();

	protected V getEntityViewInternal(String _LocationKey)
	{
		if (_LocationKey == null)
		{
			return null;
		}
		else
		{
			Key locationKey = KeyFactory.stringToKey(_LocationKey);
			V result = cashe.get(locationKey);
			if (result == null)
			{
				try
				{
				    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		            Entity location = datastore.get(locationKey);
		            result = produceViewFormEntity(location);
		            cashe.put(locationKey, result);
		            return result;
				}
				catch(EntityNotFoundException ex)
				{
					return null;
				}
			}
			else
			{
			    return result;
			}
		}
	}

	protected abstract V produceViewFormEntity(Entity _Entity);

}
